import { observable, action, useStrict, computed, asMap, toJS } from 'mobx';
import { Share ,RouteLayout} from 'weaver-mobile-page';
import { Tools ,Bubble} from 'weaver-mobile';
import BaseStore from './BaseStore';
import * as API_REQ from '../apis/form';
import base from '../util/base';
import { _ } from '../util/pcPublic';
import * as EmSDK from "../util/emSDK";
import * as SignUtil from "../util/SignUtil";
import * as VariableKeys from "../constants/variableKey";
import { cloneDeep } from 'lodash';
import * as Util from '../util/formUtil';
// import some from 'lodash/some';
// import filter from 'lodash/filter';

const initState = {
    rightMenu: {},
    submitParam: {},
    markInfo: {},
    btnDisabled : true
}

export class OperateStore extends BaseStore{

    @observable rightMenu;     //操作菜单
    @observable submitParam;
    @observable markInfo;  //签字意见输入框相关信息
    @observable btnDisabled = true;
    @observable showBottomBtn = false;

    @observable reWithDrawInfo  = {};
    @observable isRemind = '1';

    //操作菜单名称
    rightBtnName = {};

    /**********************by lijia 2018-12-28 */
    @observable share = new Share.Store({ route: '/req', id: 'share' });
    msgInfo = {};
    shareParams = {};
    browserConfig = {};
    /**********************by lijia 2018-12-28 */
    @observable cordDatas='';
    @observable layout = new RouteLayout.Store({ route: '/req',id:'follow' });
    constructor(){
        super();
        this.resetState();
        this.loadRightMenu = this.loadRightMenu.bind(this);
        this.setRightMenu = this.setRightMenu.bind(this);
        this.loadMarkInfo = this.loadMarkInfo.bind(this);
        this.changeSubmitParam = this.changeSubmitParam.bind(this);
        this.setSubmitToNodeId = this.setSubmitToNodeId.bind(this);
        this.controllBottomBtnDisable = this.controllBottomBtnDisable.bind(this);
    }
    @action
    setState = (params = {}) => {
        Object.keys(params).forEach((key) => {
            this[key] = params[key];
        });
    }
    @computed get isRichText(){
        const signParams = toJS(this.markInfo);
        const {extendParams = {}} = signParams;
        const {mobileSignInputRichText = false} = extendParams;
        return mobileSignInputRichText;
    }

    @action('加载右键菜单')
    loadRightMenu(queryParams){
        const params = {...base.wfGlobalStore.commonApiParam};
        //提交确认参数
        params.isaffirmanceSrc = queryParams.isaffirmanceSrc || "";
        params.isaffirmance = queryParams.isaffirmance || "";
        params.reEdit = queryParams.reEdit || "";
        API_REQ.getRightMenu(params).then(data =>{
			data && data.rightMenus&&data.rightMenus.sort((o1,o2) =>{
				return o1.order - o2.order;
            });
            this.setRightMenu(data);
		});
    }

    @action('设置操作菜单')
    setRightMenu(data={}){
        const {showShareBtn,ding}=Tools;
        const {checkDing}=ding;
        data.rightMenus = data.rightMenus.filter(item =>{
            return item.isMobile === true;
        });
        let _data = cloneDeep(data);
        this.checkShareBtn(_data, false,false);
        Promise.all([showShareBtn(), checkDing()]).then(([res1,res2]) => {
            let  { show,data:resData={}}=res1;
            let { shareWorkflow=0 } = resData;
            const {showDing}=res2;
            shareWorkflow = show == true && shareWorkflow == 1;
            this.checkShareBtn(data, shareWorkflow, showDing);
        });
        
    }

    checkShareBtn = (data, shareWorkflow,showDing) => {
        const tabKey = base.wfGlobalStore.tabKey;
        const {mobile_odoc_hidwfbtn = false} = base.wfLayoutStore.odocInfo;
        const {clearButten = false} = base.allStores.secondAuthStore;
        if (!shareWorkflow) { //&& window.em && window.em.checkJsApi && window.em.checkJsApi("sendMsg")
            data.rightMenus = data.rightMenus.filter(item => item.type !== "BTN_SHARE");
        }
        let inDingPc = window.inDingPc && window.inDingPc();
        if (!showDing || inDingPc) { 
            data.rightMenus = data.rightMenus.filter(item => item.type !== "BTN_DING");
        }
        //记录操作名称
        data.rightMenus.map(v => {
            this.rightBtnName[v.type] = v.menuName;
        })
        this.rightMenu = data;
        this.showBottomBtn = data.rightMenus.length > 0;
        //跳转至相关交流Tab页不显示底部按钮
        if(tabKey !== 'communicate' && (tabKey == "odoc" && mobile_odoc_hidwfbtn == true ? false : true)&&clearButten == false) {
            EmSDK.controlBottomBtn('/req');
        }
    }

    @action('加载签字意见输入信息')
    loadMarkInfo(){
        const {isHideInput = '0'} = base.wfGlobalStore.commonParam;
        if(isHideInput != '1') {
            let signInputParams = {...base.wfGlobalStore.baseParam};
            const wfSignInputStore = base.allStores.wfSignInputStore;
            const {batchControlVariableMap} = wfSignInputStore;
            API_REQ.getSignInput(signInputParams).then(data =>{
                this.setMarkInfo(data);
                const {remarkInfo = {},remarkquote = [],extendParams = {}} = data;
                const {mobileSignInputNeedBtns = true} = extendParams;
                //设置默认值到submitParams
                const updateParams = {
                    'field-annexupload':remarkInfo['field-annexupload'],
                    'signdocids':remarkInfo['signdocids'],
                    'signworkflowids':remarkInfo['signworkflowids'],
                    'remark':remarkInfo['remark'],
                    'remarkLocation':remarkInfo['remarkLocation']
                };
                this.changeSubmitParam(updateParams);
                remarkInfo[VariableKeys.SIGN_REMARK_QUOTE] = remarkquote;
                batchControlVariableMap(SignUtil.formatRemarkInfo(remarkInfo));
                this.controllBottomBtnDisable(false);
                base.allStores.wfSignInputStore.setShowIconBtnList(mobileSignInputNeedBtns);
                base.allStores.wfSignInputStore.initHandWritingData();
            });
        } else {
            base.allStores.wfSignInputStore.setShowIconBtnList(false);
            this.controllBottomBtnDisable(false);
        }
    }

    @action
    setMarkInfo(data ={}){
        this.markInfo = data;
    }

    @action('改变提交参数')
    changeSubmitParam(param={}){
        this.submitParam = {...this.submitParam, ...param};
    }

    @action('设置提交到指定节点')
    setSubmitToNodeId(isFromSubmitToReject = false){
        const { isSubmitDirectNode,lastnodeid } = this.rightMenu;
        const {commonParam} = base.wfGlobalStore;
        const {canSubmitToRejectNode = true} = commonParam;
        if((isSubmitDirectNode == "1" || isFromSubmitToReject) && canSubmitToRejectNode){
            this.changeSubmitParam({SubmitToNodeid:lastnodeid});
        }
    }

    @action('重置状态')
    resetState(){
        this.changeState(initState);
        this.resetVariableMap();
    }

    controllBottomBtnDisable(flag){
        this.btnDisabled = flag;
        //底部按钮禁用
        if(EmSDK.judgeApiSupport('userInteractionDisabled') && flag) {
            EmSDK.emClient.userInteractionDisabled({});
        }
        if(EmSDK.judgeApiSupport('userInteractionEnabled') && !flag) {
            EmSDK.emClient.userInteractionEnabled({});
        }
    }

    /**********************by lijia 2018-12-28 */
    setShareMsgInfo = () => {
        const { wfGlobalStore } = base;
        const { urlParams, commonParam, invalidParam} = wfGlobalStore;
        const { f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
        const { requestname } = invalidParam;
        const { requestid, firstSharer } = urlParams;
        let sharer_new = firstSharer ? firstSharer : f_weaver_belongto_userid;
        this.msgInfo = {
            content: requestname, // 分享标题（必填）
            sysid: window.localStorage.emobile_ec_id, // EM中添加的集成系统的ID (必填: 按照demo给的传)
            linkurl: "/common/chatResource/view.html?resourcetype=0&resourceid=" + requestid + "&isfromchatshare=1&sharer=" + f_weaver_belongto_userid + "&firstSharer=" + sharer_new, // 消息链接地址（必填）
            canforward: 1, // 消息是否允许转发 1：是（默认） 0：否
            callbackurl: "/api/common/chatResource/addshare?resourcetype=0&resourceid=" + requestid + "&isfromchatshare=1&firstSharer=" + sharer_new,
            sharetypename: "流程", //消息类型显示标题，没有则按sharetype显示
            opentype: 1, //移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
            opentype_pc: 2, //PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
            sharetype: "workflow", // 分享数据类型："doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
            shareid: requestid+"", // 分享的数据ID（必填）
        }
        this.shareParams = {
            "resourcetype": 152,
            "resourceid": requestid,
            "firstSharer": sharer_new,
            "f_weaver_belongto_userid":f_weaver_belongto_userid,
            "f_weaver_belongto_usertype":f_weaver_belongto_usertype
        }
        this.browserConfig = {
            "extendTabs": [
                {
                    "name": "",
                    "key": "",
                    "url":""
                }
            ]
        }
    }
    /**********************by lijia 2018-12-28 */


    /**
     * 获取参数，用于判断是否支持文档签批
     */
    getMobileWFOffice = () => {
        API_REQ.getMobileWFOffice().then(res => {
            const {  mobileWFOffice=0, mobilePDFSign=1 } = res;
            this.batchControlVariableMap({
                mobileWFOffice,
                mobilePDFSign
            })
        })
    }

    /**
     * 获取撤回参数
     */
    getReqWithDrawInfo = () => {
        const {baseParam = {}} = base.wfGlobalStore;
        baseParam.actionType = 'getSettings';
        API_REQ.requestWithDraw(baseParam).then(data => {
            this.reWithDrawInfo  = data;
            const {showSignInput} = base.allStores.wfSignInputStore;
            showSignInput();
        });
    }

    /**
     * 撤回提交
     */
    reqWithDrawSubmit = () => {
        const {allowRemind, recallNodeName,recallNodeId,doPreOperate} = this.reWithDrawInfo;
        const {baseParam = {}} = base.wfGlobalStore;
        const {remark = {},lastoperator,lastOperateDate,lastOperateTime,currentdate,currenttime,requestid} = this.submitParam;
        const signInfoDatas = SignUtil.getSignInfoDatas();
        let submitParams = {
            ...baseParam,
            actionType: 'submit',
            'isRemind':this.isRemind,
            remark,
            ...signInfoDatas,
            recallNodeId,doPreOperate,
            lastoperator,
            lastOperateDate,
            lastOperateTime,
            currentdate,
            currenttime
        };
        base.wfGlobalStore.setLoading(true);
        API_REQ.requestWithDraw(submitParams).then((data = {}) => {
            base.wfGlobalStore.setLoading(false);
            const {msg,result} = data
            if (result == "success") {
                Bubble.success(msg, 2);
                Util.reloadRequestPage({requestid});
            } else {
                Bubble.error(msg);
            }
        });
    }
}